﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace AudioDemo.View
{
    /// <summary>
    /// name1.xaml 的交互逻辑
    /// </summary>
    public partial class name1 : Window
    {
        public name1()
        {
            InitializeComponent();

//后台添加name 的元素
Label lbl1 = new Label();
lbl1.Content = "张三丰";
lbl1.Name = "lbl1"; //这样指定的无法通过FindName（）查找到
panelOne.Children.Add(lbl1);


TextBlock block = new TextBlock();
block.Text = "海上生明月";
panelOne.RegisterName("block1", block); //将block1名称注册到panelOne上
panelOne.Children.Add(block);
        }

        private void btn1_Click(object sender, RoutedEventArgs e)
        {
//使用FindName（） 查找
TextBox txtOne = this.FindName("txtOne") as TextBox;
if (txtOne != null)
{
    MessageBox.Show(txtOne.Text); //可以访问到
}
TextBox txtTwo = btn1.FindName("txtOne") as TextBox;
if (txtTwo != null)
{
    MessageBox.Show(txtTwo.Text); //也可以访问到
}
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
//查找后台添加的元素，没有找到
Label lbl1 = this.FindName("lbl1") as Label;
if (lbl1 != null)
{
    MessageBox.Show(lbl1.Content.ToString());
}

//从当前窗口获取,可以访问到
TextBlock block1 = btn1.FindName("block1") as TextBlock;
if (block1 != null)
{
    MessageBox.Show(block1.Text);
}
//从Panel获取，可以访问到
TextBlock block2 = panelOne.FindName("block1") as TextBlock;
if (block2 != null)
{
    MessageBox.Show("panelOne:"+block2.Text);
}
        }
    }
}
